package com.yuanda.erp9.syn.exception;

import com.yuanda.erp9.syn.entity.CmsOtherWarnLogEntity;
import com.yuanda.erp9.syn.service.erp9.CmsOtherWarnLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * @Description: 全局的的异常拦截器（拦截所有的控制器）
 */
@RestControllerAdvice
@Order(-1)
@Slf4j
public class GlobalExceptionHandler {


    @Resource
    private CmsOtherWarnLogService cmsOtherWarnLogService;


    /**
     * @Description: 目标服务器错误
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/410:21
     */
    @ExceptionHandler(TargetServerException.class)
    public void targetServerException(TargetServerException e) {
        log.error("全局异常拦截器=》{}",e.toString());
        String message = e.getMessage();
        CmsOtherWarnLogEntity entity = new CmsOtherWarnLogEntity();
        entity.setSupplier(e.getSupplier());
        entity.setFileName(e.getFileName());
        entity.setWarnLog(message);
        entity.setCreateTime(LocalDateTime.now().toString());
        cmsOtherWarnLogService.addOtherWarnLogEntity(entity);
    }


    /**
     * @Description: 服务准备阶段错误
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/1/410:21
     */
    @ExceptionHandler(ServerPrepareException.class)
    public void serverPrepareException(ServerPrepareException e) {
        log.error("全局异常拦截器=》{}",e.toString());
        String message = e.getMessage();
        CmsOtherWarnLogEntity entity = new CmsOtherWarnLogEntity();
        entity.setSupplier(e.getSupplier());
        entity.setFileName(e.getFileName());
        entity.setWarnLog(message);
        entity.setCreateTime(LocalDateTime.now().toString());
        cmsOtherWarnLogService.addOtherWarnLogEntity(entity);
    }


    /**
     * @Description: 程序未知异常
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2023/2/2314:46
     */
    @ExceptionHandler(Exception.class)
    public void undefinedException(Exception e) {
        log.error("全局异常拦截器=》{}",e.toString());
        CmsOtherWarnLogEntity entity = new CmsOtherWarnLogEntity();
        entity.setSupplier(9999);
        entity.setFileName("未知");
        entity.setWarnLog("异常信息：{" + e + "}, 异常错误抛出点: {" + e.getStackTrace()[0] + "}");
        entity.setCreateTime(LocalDateTime.now().toString());
        cmsOtherWarnLogService.addOtherWarnLogEntity(entity);
    }


}
